from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password, check_password

from myadmin import models
from .indexViews import getNavData


# Create your views here.


# 前台 - 注册
def register(request):
    if request.method == 'GET':
        context = {'classify':getNavData()}
        return render(request,'myhome/register.html',context)
    else:
        # 接收表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        data.pop('repassword')

        # 密码加密
        data['password'] = make_password(data['password'])

        # 判断是否注册成功
        try:
            # 添加数据
            userobj = models.Users(**data)
            userobj.save()
            url = reverse('myhome_login')
            return HttpResponse(f'<script>alert("注册成功");location.href="{url}";</script>')
        except:
            return HttpResponse(f'<script>alert("注册失败");history.back();</script>')


# 前台 - 登陆
def login(request):
    if request.method == 'GET':
        context = {'classify':getNavData()}
        return render(request,'myhome/login.html',context)
    else:
        # 接收表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        nextpath = request.GET.get('nextpath','/')

        try:
            # 根据手机号获取用户
            userobj = models.Users.objects.get(phone=data['phone'])
            # 验证密码是否正确
            if check_password(data['password'],userobj.password):
                # 账号密码正确，把用户记录到session中
                request.session['vipUser'] = {'id':userobj.id,'username':userobj.username}
                # url = reverse('myhome_index')
                return HttpResponse(f'<script>alert("登陆成功");location.href="{nextpath}"</script>')
            else:
                return HttpResponse('<script>alert("账号或密码错误");history.back();</script>')
        except:
            return HttpResponse('<script>alert("账号或密码错误");history.back();</script>')


# 前台 - 退出登录
def logout(request):
    request.session['vipUser'] = ''
    nextpath = request.GET.get('nextpath', '/')
    # 跳转回退出登录时所在的页面
    return HttpResponse(f'<script>alert("已退出登陆");location.href="{nextpath}";</script>')


# 注册 - 验证手机号是否已经存在
def checkphone(request):
    # 接收用户输入的手机号
    phone = request.GET.get('phone')
    # 根据手机号查找用户对象
    n = models.Users.objects.filter(phone=phone).count()
    if n:
        return JsonResponse({'code':1,'msg':'手机号码已经注册'})
    else:
        return JsonResponse({'code':0,'msg':'手机号码可用'})


# 前台 - 联系我们
def contact(request):
    context = {'classify':getNavData()}
    return render(request,'myhome/contact.html',context)
